package com.app.controller.fileTransfer;

import com.app.model.response.RetCode;
import com.app.model.response.RetStatus;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lichaojie on 2017/4/22. It's a beautiful day.
 */
@RequestMapping(value = "/image")
@RestController
public class FileTransferController {


    @RequestMapping(value = "/getToken")
    public RetStatus getToken(){
        final String accessKey = "C9VbYUI2FuUSf4OM_Fu20Obbtkl0e3RKKS1iO4ia";
        final String secretKey = "WDVhFherV40lWeYgzg_Sn6igYN3x7_4D_V49luQf";
        final String bucket = "qiniu-photo";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        //System.out.println(upToken);

        Map<String,String> map = new HashMap<>();
        map.put("token",upToken);

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(map);

        return retStatus;
    }

    @RequestMapping(value = "/apkDownload", method = RequestMethod.GET)
    public void testDownload(HttpServletResponse res) {
        String fileName = "yuanlai-v1.1.0.apk";
        //res.setHeader("content-type", "application/octet-stream");
        //res.setContentType("application/octet-stream");
        res.setHeader("content-type","application/vnd.android.package-archive");//表明需要传输的是apk文件
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            File file = new File("/usr/tomcat/apache-tomcat-8.5.12/" + fileName);

            res.setHeader("Content-Length", Long.toString(file.length()));

            FileInputStream fileInputStream = new FileInputStream(file);
            bis = new BufferedInputStream(fileInputStream);
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }


}

